﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using TESTCommons.ConvertTpye;
using TESTCommons.HttpHelper;
using TestModel.SysManage;

namespace TestManage.Infrastructure.CustomAttribute
{
    public class AopActionFilterAttribute : ActionFilterAttribute
    {
        private bool _IsExecute { get; set; }
        /// <summary>
        /// 后台登陆
        /// </summary>
        private bool _IsFrontDesk { get; set; }

        public AopActionFilterAttribute(bool IsExecute = true, bool IsFrontDesk = true)
        {
            this._IsExecute = IsExecute;
            this._IsFrontDesk = IsFrontDesk;
        }

        /// <summary>
        /// 每次请求Action之前发生，，在行为方法执行前执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        { 
            if (this._IsExecute)
            {
                //登陆超时验证
                this.CheckedLoginAccount(context);
            }
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 检查登录帐户
        /// </summary>
        private void CheckedLoginAccount(ActionExecutingContext context)
        {
            AccountModel account = WebHelper.GetSession<AccountModel>("session_account");
            if (account == null || account.UserID.ToGuid() == Guid.Empty)
            {
                if (this._IsFrontDesk)
                {
                    context.Result = new RedirectResult("~/FrontDesk/Login/Index");
                }
                else
                {
                    context.Result = new RedirectResult("~/Login/Index");
                }
            }
        }
    }
}
